package single_game.logic.race_simulator;

import java.util.ArrayList;

import main.CyclingManager;
import data.Cyclist;
import single_game.logic.race_simulator.race_team.RaceRider;

public class Group {
	
	public int groupId,
			   actualTerrain;
	public ArrayList<RaceRider> riders, 
								relayGroup;
	public double driven = 0.0, 
				  pace,
				  speed;
	private ArrayList<Cyclist> cyclists;
	
	public Group(int groupId, ArrayList<RaceRider> riders) {
		this.groupId = groupId;
		this.riders = riders;
		relayGroup = new ArrayList<RaceRider>();
		cyclists = CyclingManager.getInstance().cyclists;
		initializeGroup();
	}
	
	
	public void initializeGroup() {
		setGroupId(groupId);
	}
	
	
	public void setGroupId(int id) {
		groupId = id;
		for (RaceRider rider: riders)
			rider.setGroupId(id);
		
		for (RaceRider rider: relayGroup)
			rider.setGroupId(id);
	}
	
	
	public void removeRider(RaceRider rider) {
		for (int i = 0; i < riders.size(); i++) {
			if (riders.get(i) == rider) {
				riders.remove(rider);
				if (rider.getAction().equals("Relay") || rider.getAction().equals("Relay Queue"))
					removeFromRelayGroup(rider);
				break;
			}
		}
	}
	
	public void addRider(RaceRider rider) {
		riders.add(rider);
		rider.setGroupId(groupId);
	}
	
	
	public void addToRelayGroup(RaceRider rider) {
		print();
		relayGroup.add(rider);
		riders.remove(rider);
		print();
		System.out.println("Group: Add to relay");
	}
	
	
	public void removeFromRelayGroup(RaceRider rider) {
		for (RaceRider cyclist: relayGroup) {
			if (cyclist == rider) {
				relayGroup.remove(rider);
				riders.add(rider);
				break;
			}
		}
	}

	
	public void changeRelay() {
		if (relayGroup.size() >= 2) {			
			RaceRider rider = relayGroup.get(0);
			rider.setAction("Relay Queue");
			relayGroup.remove(0);
			relayGroup.get(0).setAction("Relay");
			relayGroup.add(rider);
		}
	}
	
	
	public Boolean inRelayGroup(RaceRider rider) {		
		for (int i = 0; i < relayGroup.size(); i++)
			if (relayGroup.get(i) == rider)
				return true;
		
		return false;	
	}
	
	
	public double setPace() {		
		RaceRider rider;
		actualTerrain = Race.getInstance().stage[(int)driven];
		if (relayGroup.size() >= 1)
			rider = relayGroup.get(0);
		else
			rider = riders.get(0);
		
		pace = RaceSimulatorOperations.setPace(rider, actualTerrain, this); 
		
		if (relayGroup.size() >= 1) 
			return pace;
		else {
			pace = pace - 15;
			return pace;
		}		
	}	
	
	public void print() {
		int cnt = 0;
		
		for (RaceRider rider: relayGroup) {
			System.out.println(cnt+". Group id: inRelay-> "+groupId+" "+cyclists.get(rider.getCyclistId()).getSurname()+" Action: "+rider.getAction());
			cnt++;
		}
		
		for (RaceRider rider: riders) {
			System.out.println(cnt+". Group id: "+groupId+" "+cyclists.get(rider.getCyclistId()).getSurname()+" Action: "+rider.getAction());
			cnt++;
		}
	}
}
